package com.draven.mybatis.session;

import com.draven.mybatis.executor.DravenExecutor;
import com.draven.mybatis.mapping.DravenEnvironment;

import com.draven.mybatis.transaction.DravenTransactionFactory;



import org.apache.ibatis.session.ExecutorType;


import org.apache.ibatis.session.TransactionIsolationLevel;
import org.apache.ibatis.transaction.Transaction;


public class DravenDefaultSqlSessionFactory implements DravenSqlSessionFactory {
  DravenConfiguration dravenConfiguration;

  public DravenDefaultSqlSessionFactory(DravenConfiguration dravenConfiguration) {
    this.dravenConfiguration = dravenConfiguration;
    System.out.println("=============DravenDefaultSqlSessionFactory 初始化完成============");
  }

  @Override
  public DravenSqlSession openSqlSession() {
    return openSessionFromDataSource(dravenConfiguration.getDefaultExecutorType(), null, false);
  }

  private DravenSqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,
                                                     boolean autoCommit) {
    final DravenEnvironment environment = dravenConfiguration.getDravenEnvironment();
    final DravenTransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
    Transaction tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
    final DravenExecutor executor = dravenConfiguration.newExecutor(tx, execType);
    return createSqlSession(dravenConfiguration, executor, autoCommit);
  }

  private DravenTransactionFactory getTransactionFactoryFromEnvironment(DravenEnvironment environment) {
    return environment.getTransactionFactory();
  }

  protected DravenSqlSession createSqlSession(DravenConfiguration configuration, DravenExecutor executor, boolean autoCommit) {
    return new DravenDefaultSqlSession(configuration, executor, autoCommit);
  }


}
